/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package businesscard.DAO;

import bc.entity.Quyen;
import bc.entity.User;
import bc.util.HibernateUtil;
import java.security.MessageDigest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Welcome
 */
public class UserDAO {
     private Session session;
    public UserDAO(){
        SessionFactory factory= HibernateUtil.getSessionFactory();
        this.session=factory.getCurrentSession();
    }
    public void Save(User A){
        try{
            session.getTransaction().begin();
            session.save(A);
            session.flush();
            session.getTransaction().commit();
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
    }
    
    // check username & password
    public User authenticate(String username, String password){
        try{
            session.getTransaction().begin();
            String sql="from User where USER = ? and PASSWORD = ?";
            Query query=session.createQuery(sql);
            query.setString(0, username);
            query.setString(1, password);
            
            User result=(User)query.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            return result;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return null;
    }
    
    public void update(User A,Integer id_user){
        try{
            session.getTransaction().begin();
            User account=(User)session.get(User.class, id_user);
            account.setUser(A.getUser());
            account.setPassword(A.getPassword());
            account.setCmnd(A.getCmnd());
            account.setDiachi(A.getDiachi());
            account.setEmail(A.getEmail());
            account.setGioitinh(A.getGioitinh());
            account.setHinhanh(A.getHinhanh());
            account.setQuanhuyen(A.getQuanhuyen());
            account.setNgaysinh(A.getNgaysinh());
            account.setPoint(A.getPoint());
            account.setQuyen(A.getQuyen());
            account.setSdt(A.getSdt());
            session.update(account);
            session.flush();
            session.getTransaction().commit();
        }catch(Exception e){
        if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
    }
   public void updatePass(String username, String newpass){
        try{
            session.getTransaction().begin();
            String sql="from User where user = ? ";
            Query query=session.createQuery(sql);
            query.setString(0, username);
            User result=(User)query.uniqueResult();
                result.setPassword(newpass);
                session.update(result);
                session.flush();
                session.getTransaction().commit(); 
        }catch(Exception e){
        if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
    }
    public void delete(int id){
        try{
            session.getTransaction().begin();
            session.delete(session.get(User.class, id));
            session.flush();
            session.getTransaction().commit();
        }catch(Exception e){
        if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
    }
    public boolean checkUser(String username) {
        try{
            session.getTransaction().begin();
            String sql="from User where USER = ?";
            Query query=session.createQuery(sql);
            query.setString(0, username);            
            User result=(User)query.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            if(result==null)
            return false;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return true;
    }
    public int getUser(String username){
        try{
            session.getTransaction().begin();
            String sql="from User where USER = ?";
            Query query=session.createQuery(sql);
            query.setString(0, username);            
            User result=(User)query.uniqueResult();
            int id=result.getIdUser();
            session.flush();
            session.getTransaction().commit();
            return id;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return 0;
    }
     public User getUser2(String username){
        try{
            session.getTransaction().begin();
            String sql="from User where user = ?";
            Query query=session.createQuery(sql);
            query.setString(0, username);       
            User result=(User)query.uniqueResult();
    
            session.flush();
            session.getTransaction().commit();
            return result;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return null;
    }
     public String getHinhanh(String username){
         try{
            session.getTransaction().begin();
            String sql="from User where user = ?";
            Query query=session.createQuery(sql);
            query.setString(0, username);       
            User result=(User)query.uniqueResult();
            String hinh=result.getHinhanh();
            session.flush();
            session.getTransaction().commit();
            return hinh;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return "";
     }
     
     public String getDC(String username){
         try{
            session.getTransaction().begin();
            String sql="from User where user = ?";
            Query query=session.createQuery(sql);
            query.setString(0, username);       
            User result=(User)query.uniqueResult();
            String diachi=result.getDiachi();   
            String tinh=result.getQuanhuyen().getThanhpho().getThanhpho();
            String huyen=result.getQuanhuyen().getQuanhuyen();
            diachi=diachi+", huyện "+huyen+", "+ "tỉnh "+tinh;
            session.flush();
            session.getTransaction().commit();
            return diachi;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return "";
     }
     
     public String getMail(String username){
         try{
            session.getTransaction().begin();
            String sql="from User where user = ?";
            Query query=session.createQuery(sql);
            query.setString(0, username);       
            User result=(User)query.uniqueResult();
            String email=result.getEmail();
            session.flush();
            session.getTransaction().commit();
            return email;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return "";
     }
    public boolean checkEmail(String email) {
        try{
            session.getTransaction().begin();
            String sql="from User where email = ?";
            Query query=session.createQuery(sql);
            query.setString(0, email);            
            User result=(User)query.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            if(result==null)
            return false;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return true;
    }
    public boolean checkPass(String pass) {
        try{
            session.getTransaction().begin();
            String sql="from User where password = ?";
            Query query=session.createQuery(sql);
            query.setString(0, pass);            
            User result=(User)query.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            if(result==null)
            return false;
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return true;
    }
    public void updateHinh(String username, String hinh){
        try{
            session.getTransaction().begin();
            String sql="from User where user = ? ";
            Query query=session.createQuery(sql);
            query.setString(0, username);
            User result=(User)query.uniqueResult();
                result.setHinhanh(hinh);
                session.update(result);
                session.flush();
                session.getTransaction().commit(); 
        }catch(Exception e){
        if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
    }
    public void AddPoint(String username, int newpoint){
        try{
            session.getTransaction().begin();
            String sql="from User where user = ? ";
            Query query=session.createQuery(sql);
            query.setString(0, username);
            User result=(User)query.uniqueResult();
                result.setPoint(newpoint);
                session.update(result);
                session.flush();
                session.getTransaction().commit(); 
        }catch(Exception e){
//       if(session.getTransaction().isActive())
//                session.getTransaction().rollback();
            e.printStackTrace();
        }
    }
    public  String md5(String msg) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(msg.getBytes());
            byte byteData[] = md.digest();
            //convert the byte to hex format method 1
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }
            return  sb.toString();
        } catch (Exception ex) {
            return "";
        }
    }
     /*test*/
        public List<User> getAllUser() throws SQLException, ClassNotFoundException{
        List<User> list =new ArrayList<User>();
        try{
            session.getTransaction().begin();
            String sql="from User";
           Query query =session.createQuery(sql);
            list=query.list();
           session.flush();
            session.getTransaction().commit();
            
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
      
         }
          return list;
    }
      

    public List<User> getUserByQuyen(Quyen q) {

        List<User> ur = new ArrayList<User>();

        try {
            session.getTransaction().begin();

            String sql = "from User where quyen=?";
            Query query = session.createQuery(sql);
            query.setEntity(0, q);
            ur = query.list();
            session.flush();
            // session.getTransaction().commit();
            return ur;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return ur;

    }

    public List<User> getUserByQuan(int idquan) {
        session.getTransaction().begin();
        List<User> result = new ArrayList<User>();
        String sql = "from User where ID_QUANHUYEN ?";
        try {
            Query query = session.createQuery(sql);
            query.setInteger(0, idquan);
            result = query.list();
            session.flush();
            session.getTransaction().commit();
            return result;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return result;

    }

    public User getUserbyID(int id) {
        try {
            session.getTransaction().begin();
            String sql = "from User where idUser = ?";
            Query query = session.createQuery(sql);
            query.setInteger(0, id);
            User result = (User) query.uniqueResult();
            // int id = result.getIdUser();
            session.flush();
            session.getTransaction().commit();
            return result;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }

    public List<User> searchlikename(String name) {
        session.beginTransaction().begin();
        String sql = "from User where user like ?";
        try {
            Query query = session.createQuery(sql);
            query.setString(0, "%" + name + "%");
            List resultlist = query.list();
         //   session.getTransaction().commit();
            session.flush();
            return resultlist;
        } catch (Exception ex) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            ex.printStackTrace();
        }
        return null;

    }
        //phan Nga
     
 /*   public static void main(String[] args) {
    
        UserDAO urdao= new UserDAO();
        try{
        List<User> listur= urdao.getAllUser();
        for(int i=0; i<listur.size();i++)
        {
            System.out.println("user thu:"+i);
             System.out.println(listur.get(i).getUser());
            System.out.println(listur.get(i).getEmail());
            System.out.println(listur.get(i).getDiachi());
        }
        }catch (Exception ex){
            ex.printStackTrace();
            
           
        }
    
    }*/
    /*    public static void main(String[] args) {
            UserDAO urdao= new UserDAO();
        String a="0U9N6KRIL4BIIUR";
        String b=urdao.md5(a);
            System.out.println("mã hóa: "+b);
    }
    */
        public static void main(String[] args) {
        UserDAO urdao= new UserDAO();
        //String hinh=urdao.getDC("huyen");
          //  System.out.println(": "+hinh);
        int p=10;
        urdao.AddPoint("test", p);
           // System.out.println();
    }
      
}
